package com.yorick.common.config.executor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @program: YorickThreadPool
 * @description: 自定义线程池
 * @author: Yorick
 * @create: 15/4/2022
**/
@Configuration
@EnableAsync
@Slf4j
public class ExecutorConfig implements AsyncConfigurer {
    @Value("${yorick.threadPool.corePoolSize:30}")
    private int corePoolSize;
    @Value("${yorick.threadPool.queueCapacity:500}")
    private int queueCapacity;
    @Value("${yorick.threadPool.maxPoolSize:100}")
    private int maxPoolSize;
    @Value("${yorick.threadPool.keepAliveSeconds:60}")
    private int keepAliveSeconds;

    @Bean(name = "yorickThreadPool")
    public Executor yorickThreadPool(){
        ThreadPoolTaskExecutor executor=new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);//线程池核心线程数量（默认开启数量）
        executor.setQueueCapacity(queueCapacity);//配置队列大小
        executor.setMaxPoolSize(maxPoolSize);//线程池最大线程数量，如果超出进入队列
        executor.setKeepAliveSeconds(keepAliveSeconds);//非核心线程超时时长，超时会被回收
        executor.setThreadNamePrefix("YorickThreadPool--");//线程名前缀
        executor.setWaitForTasksToCompleteOnShutdown(true);//用来设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
        executor.setRejectedExecutionHandler(
                (Runnable r,ThreadPoolExecutor exe) ->{
                    log.warn("YorickThreadPool-- 当前线程池队列已满！");
                });
        executor.initialize();
        log.info("--------------线程池初始化成功--------------");
        return executor;
    }

    @Override
    public Executor getAsyncExecutor() {
        return yorickThreadPool();
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> log.error("线程池执行任务发送未知错误, 执行方法：{}", method.getName(), ex);
    }
}
